package com.edu.boot.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.edu.boot.common.api.CommonResult;
import com.edu.boot.config.UserContext;
import com.edu.boot.entity.*;
import com.edu.boot.entity.Vo.RecruitmentAllInfoVo;
import com.edu.boot.entity.Vo.RecruitmentAndSonNotesManageVo;
import com.edu.boot.entity.Vo.SResumeAndNid;
import com.edu.boot.entity.Vo.ShopAndRecruitmentVo;
import com.edu.boot.enums.UserTypeEnum;
import com.edu.boot.enums.ZWSHStatus;
import com.edu.boot.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@Controller
public class RecruitmentManageController {

    @Autowired
    RecruitmentService recruitmentService;
    @Autowired
    BannerService bannerService;
    @Autowired
    RecuritTypeService recuritTypeService;
    /**
     * 兼职列表查询（企业和管理端）
     *
     * @return
     */
    @ResponseBody
    @GetMapping("recruitment/list")
    public CommonResult list(@RequestParam(name = "currentpage") Integer current,
                                 @RequestParam(name = "pagesize") Integer size,
                                 @RequestParam(name = "recName", required = false) String recName,
                                 @RequestParam(name = "recType",required = false) String recType) {
        Page<Recruitment> page = new Page<>(current, size);
        Recruitment recruitment = new Recruitment();
        recruitment.setRecName(recName);
        recruitment.setRecType(StringUtils.isNotBlank(recType) ? Integer.valueOf(recType) : null);
        
        IPage<Recruitment> recruitmentPage = recruitmentService.getRecruitmentList(page, recruitment);
        List<Recruitment> recruitmentList = Collections.emptyList();
        if (CollectionUtil.isNotEmpty(recruitmentPage.getRecords())){
            Map<Integer, String> recuritTypeMap = recuritTypeService.getRecuritTypeMap();
            recruitmentList = recruitmentPage.getRecords()
                    .stream()
                    .map(item -> {
                        item.setShStatusMsg(ZWSHStatus.getByCode(item.getShStatus()).getDescription());
                        item.setRecTypeMsg(recuritTypeMap.get(item.getRecType()));
                        return item;
                    })
                    .collect(Collectors.toList());
        }
        recruitmentPage.setRecords(recruitmentList);
        return CommonResult.success(recruitmentPage, "获取商家列表成功！！");
    }
    
    /**
     * 修改职位信息
     * @param recruitment
     * @return
     */
    @ResponseBody
    @PostMapping("recruitment/update")
    public CommonResult recUpdate(@RequestBody Recruitment recruitment) {
        Recruitment oldRecruiment = recruitmentService.getById(recruitment.getRecId());
        if (Objects.isNull(oldRecruiment)){
           return CommonResult.failed("修改失败！数据不存在");
        }
        recruitment.setCreateTime(null);
        BeanUtils.copyProperties(recruitment,oldRecruiment);
        if(!UserTypeEnum.admin.getCode().equals(UserContext.getPid())){
            //设置状态为待审核
            oldRecruiment.setShStatus(ZWSHStatus.DSH.getCode());
        }
        boolean update = recruitmentService.updateById(oldRecruiment);
        if (!update) return CommonResult.failed("职位信息更新失败！");
        return CommonResult.success();
    }
    
    /**
     * 新增招聘职位信息
     */
    @ResponseBody
    @PostMapping("recruitment/add")
    public CommonResult addRecruitment(@RequestBody Recruitment recruitment) {
        //设置状态为待审核
        recruitment.setShStatus(ZWSHStatus.DSH.getCode());
        recruitment.setBId(UserContext.getUserId());
        recruitment.setCreateTime((DateUtil.date()));
        boolean save = recruitmentService.save(recruitment);
        if (save) return CommonResult.success(null,"添加职位信息成功！");
        return CommonResult.failed("添加职位信息失败！！");
    }
    /**
     * 删除招聘职位信息
     * @param recId
     * @return
     */
    @ResponseBody
    @GetMapping("recruitment/delete/{recId}")
    public CommonResult recDelete(@PathVariable Integer recId) {
       recruitmentService.removeById(recId);
        return CommonResult.success();
    }
    /**
     * 根据id查询招聘职位信息
     * @param recId
     * @return
     */
    @ResponseBody
    @GetMapping("recruitment/get/{recId}")
    public CommonResult recGet(@PathVariable Integer recId) {
        Recruitment recruitment = recruitmentService.getById(recId);
        return CommonResult.success(recruitment);
    }
    
    /***
     * 管理员，查询职位信息
     * @param current
     * @param size
     * @param recName
     * @param recType
     * @return
     */
    @ResponseBody
    @GetMapping("recruitment/adminList")
    public CommonResult adminList(@RequestParam(name = "currentpage") Integer current,
                             @RequestParam(name = "pagesize") Integer size,
                             @RequestParam(name = "recName", required = false) String recName,
                             @RequestParam(name = "recType",required = false) Integer recType) {
        Page<RecruitmentAllInfoVo> page = new Page<>(current, size);
    
        IPage<RecruitmentAllInfoVo> recruitmentAdminPage = recruitmentService.getRecruitmentAdminList(page, recName,
                                                                                                      recType);
        List<RecruitmentAllInfoVo> recruitmentAdminList = Collections.emptyList();
        if (CollectionUtil.isNotEmpty(recruitmentAdminPage.getRecords())){
            Map<Integer, String> recuritTypeMap = recuritTypeService.getRecuritTypeMap();
            recruitmentAdminList = recruitmentAdminPage.getRecords()
                    .stream()
                    .map(item -> {
                        item.setShStatusMsg(ZWSHStatus.getByCode(item.getShStatus()).getDescription());
                        item.setRecTypeMsg(recuritTypeMap.get(item.getRecType()));
                        return item;
                    })
                    .collect(Collectors.toList());
        }
        recruitmentAdminPage.setRecords(recruitmentAdminList);
        return CommonResult.success(recruitmentAdminPage, "获取商家列表成功！！");
    }
    
    
    @Autowired
    CommentService commentService;
    @Autowired
    CommentReplyService commentReplyService;
    @Autowired
    TopService topService;
   
    


    @Autowired
    NotesManageService notesManageService;
    @Autowired
    SResumeService sResumeService;
    /**
     * 获取商家收到的所有简历信息
     * 该方法用于获取指定商家(boss)收到的所有简历，并按招聘信息进行分组
     * @param id 商家ID
     * @return 按招聘信息分组的简历列表
     */
    @ResponseBody
    @GetMapping("managehome/rec/notes/{id}")
    public CommonResult getMyAllNotes(@PathVariable Integer id) {
        // 创建查询条件，查询指定商家ID的所有简历投递记录
        QueryWrapper<NotesManage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("boss_id",id);
        // 获取该商家收到的所有简历投递记录
        List<NotesManage> list1 = notesManageService.list(queryWrapper);
        // 创建一个Map用于存储招聘ID和对应的简历列表
        // key: 招聘ID, value: 该招聘下的所有简历列表
        HashMap<Integer,ArrayList<SResumeAndNid>> map = new HashMap<>();
        // 存储最终返回的结果列表
        List<RecruitmentAndSonNotesManageVo> recruitmentAndSonNotesManageVos = new ArrayList<>();

        // 遍历商家收到的所有简历投递记录
        for (NotesManage notesManage : list1) {
            // 如果该招聘ID在Map中不存在，说明是新的招聘信息
            if(!map.containsKey(notesManage.getRecId())){
                // 获取该简历的详细信息
                SResumeAndNid sResume = sResumeService.getOneTid(notesManage.getResumeId());
                // 创建新的简历列表
                ArrayList<SResumeAndNid> sResumeLists = new ArrayList<>();
                // 设置简历的投递记录信息
                sResume.setNid(notesManage.getNid());
                sResume.setOfferStatus(notesManage.getOfferStatus());
                sResume.setComment(notesManage.getComment());
                // 将简历添加到列表中
                sResumeLists.add(sResume);
                // 将招聘ID和对应的简历列表存入Map
                map.put(notesManage.getRecId(),sResumeLists);
            }else {
                // 如果该招聘ID已存在，则获取现有的简历列表
                ArrayList<SResumeAndNid> sResumes = map.get(notesManage.getRecId());
                // 创建新的简历列表用于更新
                ArrayList<SResumeAndNid> newsResumes = new ArrayList<>();
                // 获取新投递的简历信息
                SResumeAndNid sResume = sResumeService.getOneTid(notesManage.getResumeId());
                // 设置简历的投递记录信息
                sResume.setNid(notesManage.getNid());
                sResume.setOfferStatus(notesManage.getOfferStatus());
                sResume.setComment(notesManage.getComment());
                // 将现有简历列表复制到新列表中
                newsResumes.addAll(sResumes);
                // 添加新投递的简历
                newsResumes.add(sResume);
                // 更新Map中的简历列表
                map.put(notesManage.getRecId(),newsResumes);
            }
        }

        // 遍历所有招聘ID，构建最终的返回结果
        RecruitmentAndSonNotesManageVo recruitmentAndSonNotesManageVo = null;
        for (Object o : map.keySet().toArray()) {
            // 创建招聘信息对象
            recruitmentAndSonNotesManageVo = new RecruitmentAndSonNotesManageVo();
            // 查询招聘详细信息
            QueryWrapper<Recruitment> recruitmentQueryWrapper = new QueryWrapper<>();
            recruitmentQueryWrapper.eq("rec_id",(Integer) o);
            final Recruitment byId = recruitmentService.getOne(recruitmentQueryWrapper);
            // 设置招聘信息
            recruitmentAndSonNotesManageVo.setRecSalary(byId.getRecSalary());
            recruitmentAndSonNotesManageVo.setRecInfo(byId.getRecInfo());
            recruitmentAndSonNotesManageVo.setRecId(byId.getRecId());
            recruitmentAndSonNotesManageVo.setRecHeat(byId.getRecHeat());

            recruitmentAndSonNotesManageVo.setRecStation(byId.getRecStation());

            // 获取该招聘下的所有简历
            ArrayList<SResumeAndNid> sResumes = new ArrayList<>();
            sResumes.addAll(map.get(o));
            // 设置简历列表
            recruitmentAndSonNotesManageVo.setChildren(sResumes);

            // 将完整的招聘信息（包含简历列表）添加到结果中
            recruitmentAndSonNotesManageVos.add(recruitmentAndSonNotesManageVo);
        }
        // 返回处理后的结果
        return CommonResult.success(recruitmentAndSonNotesManageVos,"获取各个招聘信息的简历成功！！");
    }

}
